import * as echarts from '../../ec-canvas/echarts';
const Moment = require('../../utils/Moment');
const fetch = require('../../utils/fetch');
let app = getApp();

Page({
  data: {
    ifHidden: false,
    date: '',
    // 供用户选择的例假周期开始时间数组
    timeArr: [],
    index: 0,
    ec: {
      lazyLoad: true
    },
    // 显示在下面的数据
    infoObj: {
      date: "",
      time: "",
      value: 0
    }
  },
  onLoad() {
    wx.showLoading({
      title: '加载中'
    });
    wx.showShareMenu({
      withShareTicket: true
    })
    var that = this
    let user_id = app.loginUser.id;
    // 接口返回例假期字符串  20171026:20171029,20171122:20171127,...
    fetch('small/' + user_id + '/menstruation/info').then(res => {
      if (res.data.status) {
        //获取今天的时间
        var today = new Date();
        var today_time = today.getFullYear() + '/' + (today.getMonth() + 1) + '/' + today.getDate()
        // 调用方法对例假期字符串进行解析, 得到例假日期数组
        var all_cases = gainCases(res.data.data.menstruationDate);
        // 将所有例假开始时间拼成一个数组, 供用户选择使用
        var timeArr = all_cases.map(v => v[0]);
        for (var i = 0; i < timeArr.length; i++) {
          if (i == timeArr.length - 1) {
            timeArr[i] = timeArr[i] + ' - ' + today_time
          } else {
            var stop = new Date(timeArr[i + 1]).getTime() - 1000 * 60 * 60 * 24;
            var myDate = new Date(stop);
            var stop_time = myDate.getFullYear() + '/' + (myDate.getMonth() + 1) + '/' + myDate.getDate()
            timeArr[i] = timeArr[i] + ' - ' + stop_time;
          }
        }
        var first_time = timeArr[timeArr.length - 1].split(" - ")[0];
        fetch('small/' + user_id + '/info').then(res => {
          // 初始化 line, 同时渲染最新 first_time 至今的数据
          that.init_line(first_time, today_time, all_cases[timeArr.length - 1], res.data.data.physiologicalLength)
          //生理周期长度
          this.setData({
            physiologicalLength: res.data.data.physiologicalLength,
            timeArr,
            all_cases,
            index: timeArr.length - 1,
          });
          wx.hideLoading();
        })
      }
    })
  },
  onReady() {

  },
  // 折线图初始化, 挂载 lineChart 在实例上
  init_line: function (startTime, endTime, all_cases, physiologicalLength) {
    // 获取组件
    this.lineComponent = this.selectComponent("#mychart-dom-line");
    this.lineComponent.init((canvas, width, height) => {
      const lineChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      // 将 lineChart 挂载在实例上, 将来用于进行 Options 初始化
      this.lineChart = lineChart;
      this.getDataSetOption(startTime, endTime, all_cases, physiologicalLength);


      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return lineChart;
    })
  },

  // 根据时间起止日期进行 echarts 图渲染
  getDataSetOption: function (startTime, endTime, all_cases, physiologicalLength) {
    var that = this;
    var chart = this.lineChart;
    // api 需要 日期格式 2018-05-26, 接口使用 apiStartTime
    // ios 需要 日期格式 2018/05/26, 普通使用 startTime
    var apiStartTime = startTime.replace(/\//g, "-");
    var apiEndTime = endTime.replace(/\//g, "-");
    let user_id = app.loginUser.id;
    //根据例假开始时间计算易排卵期，（例假开始日期时间+生理周期长度-14）的+-3天，共7天
    var length = physiologicalLength - 14;
    var ovulation = GetDateStr(startTime, length);
    var easy_ovulation = tab(ovulation, 3)
    // 接口返回例假期字符串
    fetch(`small/${user_id}/resistances?startTime=${apiStartTime} 00:00:00&endTime=${apiEndTime} 23:59:59`)
      .then(res => {
        if (res.data.status !== 200) {
          return;
        }
        // 获取到所有 dtos数组, 每天对应一个
        var datas = res.data.data.dtos;
        var detectionData = [];
        // 将所有有佑蜜值的取出放到新数组中
        datas.forEach(v => v.dtos && detectionData.push(v));
        // 佑蜜值
        // 遍历, 由于一可能多次检测有多个 佑蜜值, 只要最大的即可
        var waterContent = detectionData.map(v => {
          var water = v.dtos[v.dtos.length - 1];
          // 遍历点, 如果大了就重新赋值
          // v.dtos.forEach(value => {
          //   water = value.waterContent > water.waterContent ? value : water;
          // });
          return water;
        });
        var surge = waterContent.filter(v => {
          if (v.ovulation == true) {
            return v
          }
        })
        // 组合解析成 echarts 需要的数据格式
        var data = echarts.util.map(waterContent, function (entry) {
          return [entry.detectionTime, entry.waterContent];
        });

        var data1 = echarts.util.map(surge, function (entry) {
          return [entry.detectionTime, entry.waterContent];
        });
        //渲染例假期
        var cases_data = echarts.util.map(all_cases, function (entry, index, arr) {
          return [arr[0].replace(/-/g, "/"), GetDateStr(arr[arr.length - 1], 1), '700']
        })
        //渲染易排卵期
        var easy = echarts.util.map(easy_ovulation, function (entry, index, arr) {
          return [arr[0], GetDateStr(arr[arr.length - 1], 1), '700']
        });
        //获取x轴的最大值max
        var max;
        if (data.length > 0) {
          let endTime = data[data.length - 1][0].split(" ")
          if (new Date(endTime[0]).getTime() > new Date(GetDateStr(easy[0][1], 1)).getTime()) {
            max = GetDateStr(data[data.length - 1][0], 1)
          } else {
            max = GetDateStr(easy[0][1], 1)
          }
        } else {
          max = GetDateStr(easy[0][1], 1)
        }

        function renderItem(params, api) {
          var yValue = api.value(2);
          var start = api.coord([api.value(0), yValue]);
          var size = api.size([api.value(1) - api.value(0), yValue]);
          var style = api.style();

          return {
            type: 'rect',
            shape: {
              x: start[0],
              y: start[1],
              width: size[0],
              height: size[1]
            },
            style: style
          };
        }
        var option = {
          tooltip: {
            trigger: 'axis',

          },
          legend: {
            data: ['佑蜜值稳定', '佑蜜值激增'],
            x: 'center',
            bottom: '6'
          },
          grid: {
            x: 30,
            x2: 15,
            y: 10,
            y2: '52',
          },
          xAxis: {
            type: 'time',
            // 设置显示周期最大间隔
            // maxInterval: 3600 * 1000 * 24 * 5,
            min: new Date(cases_data[0][0]),
            max: max,
            splitLine: {
              lineStyle: {
                color: '#ddd',
                show: true
              }
            },
            axisTick: {
              show: false,

            },
            axisLine: {
              lineStyle: {
                color: '#999999'
              }
            },
            axisLabel: {
              interval: 'auto',
              formatter: function (value) {
                let month = new Date(value).getMonth() + 1;
                let date = new Date(value).getDate()
                return month + '.' + date
              }
            },
            axisPointer: {
              label: {
                formatter: function (params) {
                  if (params.seriesData.length > 0) {
                    // 全部日期时间 2018-05-29 07:54:11
                    if (params.seriesData[0].data !== undefined) {
                      var allTime = params.seriesData[0].data[0];
                      let date = new Date(params.value);
                      var date_format = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()
                      that.setData({
                        infoObj: {
                          date: date_format,
                          time: allTime.split(" ")[1].slice(0, 5),
                          value: params.seriesData[0].data[1]
                        }
                      })
                    }
                  } else {
                    that.setData({
                      infoObj: {}
                    })
                  }
                },
              },
              lineStyle: {
                type: 'dashed'
              }
            }
          },
          yAxis: [{
            // type: 'value',
            // nameLocation: 'middle',
            // max: 700,
            // min: 0,
            // android 有兼容性问题, 如果旋转, 会不显示刻度
            // axisLabel: {
            //   interval: 0,
            //   rotate: 90
            // },
            axisLine: {
              show: false,
              lineStyle: {
                color: '#999999'
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false,
              lineStyle: {
                color: '#ddd'
              }
            }
          }, {
            show: false,
            name: '另一个y轴刻度',
            nameLocation: 'middle',
            axisLine: {
              lineStyle: {
                color: '#015DD5'
              }
            },
            axisLabel: {
              show: false
            },
            splitLine: {
              show: false
            },
          }],

          series: [{
              type: 'line',
              // name: '佑蜜值稳定',
              yAxisIndex: 1,
              showSymbol: true,
              hoverAnimation: true,
              symbolSize: 10,
              smooth: true,
              lineStyle: {
                normal: {
                  color: '#ae58ed'
                }
              },
              itemStyle: {
                normal: {
                  color: '#fc5074',
                }
              },
              markArea: {
                silent: true,
                label: {
                  position: ['50%', '100%'],
                  align: 'center',
                  verticalAlign: 'bottom'
                },
                data: [
                  [{
                    // name: '例假期',
                    xAxis: cases_data[0][0],
                    itemStyle: {
                      color: 'rgba(255,107,138,0.1)'
                    },
                    label: {
                      color: '#FF6B8A'
                    }
                  }, {
                    xAxis: cases_data[0][1]
                  }],
                  [{
                    // name: '易排卵期',
                    xAxis: easy[0][0],
                    itemStyle: {
                      color: 'rgba(255,236,206,0.3)'
                    },
                    label: {
                      color: '#57C0FF'
                    }
                  }, {
                    xAxis: easy[0][1],
                  }]
                ]
              },
              encode: {
                x: 0,
                y: 1
              },
              data: data,
            },
            {
              type: 'scatter',
              // name: '佑蜜值激增',
              yAxisIndex: 1,
              showSymbol: true,
              hoverAnimation: true,
              symbol: 'path://M1024.549 360.609c0-170.492-133.815-309.265-298.055-309.265-81.129 0-157.91 34.998-213.344 94.701-55.509-59.702-132.367-94.701-213.344-94.701C135.49 51.344 1.751 190.041 1.751 360.609c0 5.719 0.534 10.827 0.991 15.021-0.076 1.373-0.152 2.745-0.152 4.194 0 30.193 7.319 63.361 21.73 98.59 0.458 1.295 0.915 2.516 1.449 3.657 90.812 217.844 440.412 468.474 455.279 479.985 9.227 7.092 20.205 10.6 31.263 10.6 11.209 0 22.266-3.659 31.566-10.903 12.733-9.911 310.941-224.551 429.279-427.603 4.498-6.861 7.854-13.494 10.828-19.215 0.914-1.829 1.753-3.658 2.744-5.413l0.382-0.839c0.382-0.686 0.839-1.449 1.296-2.059 7.091-13.802 12.732-26.611 17.232-39.116 12.274-32.177 18.3-60.847 18.3-87.61 0-2.058-0.077-3.888-0.229-5.414C1024.093 370.979 1024.549 366.251 1024.549 360.609z',
              symbolSize: 15,
              lineStyle: {
                normal: {
                  color: 'rgba(88,160,253,1)'
                }
              },
              itemStyle: {
                normal: {
                  color: '#fc5074'
                }
              },
              encode: {
                x: 0,
                y: 1
              },
              data: data1,
            },
          ]
        };
        chart.setOption(option);
        chart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: data.length - 1,
        });
        wx.hideLoading();
      });
  },

  // 点击选择日期, 让canvas层隐藏, 解决弹出日期框被 canvas覆盖无法显示的问题
  tapHideCanvas: function (e) {
    this.setData({
      ifHidden: true
    })
  },
  // 选择日期事件
  bindPickerChange: function (e) {
    this.setData({
      infoObj: {}
    })
    wx.showLoading({
      title: '加载中'
    });
    // 用户选择的时间索引
    var index = e.detail.value;
    // 用户重新选择了日期， 重新调用 getDataSetOption 进行折线图渲染
    // getDataSetOption(startTime, endTime, all_cases, physiologicalLength)
    var timeArr = this.data.timeArr[index].split(" - ");
    var physiologicalLength = this.data.physiologicalLength;
    let all_cases = this.data.all_cases;
    this.getDataSetOption(timeArr[0], timeArr[1], all_cases[index], physiologicalLength)
    this.setData({
      index,
      ifHidden: false,
    });

  },
  //取消事件触发
  bindPickerCancel: function (e) {
    let index = this.data.index;
    let timeArr = this.data.timeArr[index].split(" - ");
    let physiologicalLength = this.data.physiologicalLength;
    let all_cases = this.data.all_cases;
    this.getDataSetOption(timeArr[0], timeArr[1], all_cases[index], physiologicalLength)
    this.setData({
      index,
      ifHidden: false,
    });
  }
});

function gainCases(casesData) { //这里是返回所有的例假时间
  var Cases = casesData.split(",")
  var all_cases = [];
  for (var i = 0; i < Cases.length; i++) {
    var time1 = (Cases[i].split(":")) //所有的例假开始跟结束
    var time2 = time1[0].substr(0, 4) + '/' + time1[0].substr(4, 2) + '/' + time1[0].substr(6, 2);
    var time3 = time1[1].substr(0, 4) + '/' + time1[1].substr(4, 2) + '/' + time1[1].substr(6, 2)
    var time4 = [];
    time4.push(time2);
    time4.push(time3)
    all_cases.push(add_date(time4[0], time4[1]))
  }
  return all_cases
}

function add_date(start_time, end_time) { //拿到开始例假跟结束例假补充中间的
  var bd = new Date(start_time),
    be = new Date(end_time);
  var bd_time = bd.getTime(),
    be_time = be.getTime(),
    time_diff = be_time - bd_time;
  var d_arr = [];
  for (var i = 0; i <= time_diff; i += 86400000) {
    var ds = new Date(bd_time + i);
    d_arr.push(ds.getFullYear() + '/' + (ds.getMonth() + 1) + '/' + ds.getDate())
  }
  return d_arr
}

function GetDateStr(a, AddDayCount) { //几天后
  a = a.replace(/-/g, "/");
  var dd = new Date(a);
  dd.setDate(dd.getDate() + AddDayCount);
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1;
  var d = dd.getDate();
  return y + "/" + m + "/" + d;
}

function tab(date, dNum) { //前后三天
  var arr = date.split('/');
  var fDay = [];
  for (var i = (parseInt(arr[2]) - dNum); i <= (parseInt(arr[2]) + dNum); i++) {
    var dd = new Date(arr[0], arr[1] - 1, i)
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期 
    var d = dd.getDate();
    fDay.push(y + "/" + m + "/" + d);
  }
  return fDay;
}


function formatDate(str) {
  // 将日期格式 从 1995-07-25 重置成 1995/07/25
  return str.replace(/-/g, '/');
}